import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'

@Component({
  selector: 'app-ex0602',
  templateUrl: './ex0602.component.html',
  styleUrls: ['./ex0602.component.scss']
})
export class Ex0602Component implements OnInit, AfterViewInit {
  protected cnv: any
  protected ctx: any

  @ViewChild('canvas')
  set canvas(ref: ElementRef) {
    this.cnv = ref.nativeElement
    this.ctx = ref.nativeElement.getContext('2d')
  }

  constructor() {
  }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    // this.draw1(this.ctx)
    // this.draw2(this.ctx)
    // this.draw3(this.ctx)
    this.draw4(this.ctx)
  }

  draw1(ctx): void {
    ctx.beginPath()
    ctx.arc(215, 125, 60, 0, 2 * Math.PI, true)
    ctx.closePath()
    ctx.stroke()

    ctx.clip()

    const image = new Image()
    image.src = 'assets/images/pic.jpg'
    image.onload = () => {
      ctx.drawImage(image, 0, 0, 300, 300)
    }
  }

  draw2(ctx): void {
    ctx.moveTo(20, 70)
    ctx.lineTo(120, 20)
    ctx.lineTo(120, 70)
    ctx.lineTo(20, 70)
    ctx.stroke()

    ctx.clip()

    const image = new Image()
    image.src = 'assets/images/pic.jpg'
    image.onload = () => {
      ctx.drawImage(image, 0, 0, 130, 130)
    }
  }

  draw3(ctx): void {
    const image = new Image()
    image.src = 'assets/images/pic.jpg'
    image.onload = () => {
      const text = '你好世界'
      ctx.font = 'bold 32px 微软雅黑'
      ctx.fillStyle = ctx.createPattern(image, 'no-repeat')
      // ctx.drawImage(image, 0, 0, 130, 130)
      ctx.fillText(text, 10, 50)
    }
  }

  draw4(ctx): void {
    const image = new Image()
    image.src = 'assets/images/pic.jpg'
    image.onload = () => {
      ctx.beginPath()
      ctx.arc(130, 60, 60, 0, 2 * Math.PI, true)
      ctx.closePath()
      ctx.fillStyle = ctx.createPattern(image, 'no-repeat')
      ctx.fill()
    }
  }
}
